//
//  SearchViewController.m
//  MoreFunTV
//
//  Created by admin on 14-10-21.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "AppDelegate.h"
#import "UIImageView+AFNetworking.h"

@interface SearchViewController (){
    __weak MatchstickDeviceController *_matchstickDeviceController;
}
@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
    
    AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    _matchstickDeviceController = delegate.matchstickDeviceController;
    //投射图标判断
    if (_matchstickDeviceController.deviceScanner.devices.count > 0) {
        self.tabBarController.navigationItem.rightBarButtonItem = _matchstickDeviceController.matchstickBarButton;
    }
    
    //监听输入法状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInputMode:) name:UITextInputCurrentInputModeDidChangeNotification object:nil];
    
    //历史搜索和热门搜索
    [self addHotView];
    
    //搜索框添加
    [self addSearch];
    
    //搜索列表
    [self addSearchTable];
    
    RequestParameter *rep = [[RequestParameter alloc]init];
    rep.portID = 4;
    rep.strPageNo = @"1";
    rep.strPageSize = @"30";
    
    [Loading showLoadingWithView:self.view];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //执行耗时操作
        //从网络获取热词信息
        _arrHot = [NetWorkingHelper getHotWordsWithRequestParameter:rep];
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程更新UI
            [Loading hiddonLoadingWithView:self.view];
            [_tableHot reloadData];
        });
    });
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //TiTle自定义
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:19.0f];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = MyLocalizedString(@"sousuo");
    self.tabBarController.navigationItem.titleView = titleLabel;
    
    _matchstickDeviceController.delegate = self;
    
    //从数据库查询历史记录信息
    _arrHistory  = [DBDaoHelper selectSearchHistory];
    _arrHHH = [[NSMutableArray alloc]init];
    for (int i = _arrHistory.count-1; i >= 0; i--) {
        [_arrHHH addObject:[_arrHistory objectAtIndex:i]];
    }
    [_tableHot reloadData];
}

- (void)shouldDisplayModalDeviceController {
    //投射按钮调用的方法
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myDevice" object:nil userInfo:nil];
}

- (void)didDiscoverDeviceOnNetwork {
    // Add the Matchstick icon if not present.
    self.tabBarController.navigationItem.rightBarButtonItem = _matchstickDeviceController.matchstickBarButton;
}

//搜索列表
-(void)addSearchTable
{
    //热门搜索列表
    _tableSearch = [[UITableView alloc]initWithFrame:CGRectMake(0, 55, kScreenWidth, 0) style:UITableViewStylePlain];
    _tableSearch.showsVerticalScrollIndicator = YES;//隐藏纵向滚动条
    _tableSearch.delegate = self;
    _tableSearch.dataSource = self;
    _tableSearch.bounces = YES;
    _tableSearch.separatorColor = [UIColor colorWithWhite:0.685 alpha:1.000];//分割线颜色
    [_tableSearch setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
    [_searchBgView addSubview:_tableSearch];
}


//搜索框添加
-(void)addSearch
{
    //底部的view
    _searchBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 55)];
    _searchBgView.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
    _searchBgView.layer.borderWidth = 1;
    _searchBgView.layer.borderColor = [[UIColor clearColor]CGColor];
    [self.view addSubview:_searchBgView];
    
    UIImageView *searchImg = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, kScreenWidth-10-50, 32)];
    [searchImg setImage:[UIImage imageNamed:@"searchImg.png"]];
    [searchImg setUserInteractionEnabled:YES];
    [_searchBgView addSubview:searchImg];
    
    //输入框
    _txtSearch = [[UITextField alloc]initWithFrame:CGRectMake(13, 1, kScreenWidth-50-26, 30)];
    _txtSearch.textColor = [UIColor blackColor];
    _txtSearch.font = [UIFont boldSystemFontOfSize:17.0f];
    _txtSearch.placeholder = MyLocalizedString(@"input2");
    _txtSearch.backgroundColor = [UIColor clearColor];
    _txtSearch.clearButtonMode = UITextFieldViewModeAlways;
    _txtSearch.keyboardType = UIKeyboardTypeDefault;
    _txtSearch.returnKeyType = UIReturnKeySearch;
    _txtSearch.delegate = self;
    [_txtSearch addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];
    [searchImg addSubview:_txtSearch];
    
    //搜索按钮
    _btnSearch = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnSearch.frame = CGRectMake(kScreenWidth-50, 0, 50, 55);
    _btnSearch.tintColor = [UIColor colorWithWhite:0.481 alpha:1.000];
    [_btnSearch setImage:[UIImage imageNamed:@"Search.png"] forState:UIControlStateNormal];
    _btnSearch.backgroundColor = [UIColor clearColor];
    _btnSearch.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    [_btnSearch addTarget:self action:@selector(clickSearch) forControlEvents:UIControlEventTouchUpInside];
    [_searchBgView addSubview:_btnSearch];
    
    //提示框  未搜索到视频时
    _promptView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+55, kScreenWidth, 0)];
    _promptView.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
    _promptView.clipsToBounds = YES;
    [self.view addSubview:_promptView];
    
    //图片
    UIImageView *imgPrompt = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth-40)/2, 10, 40, 40)];
    [imgPrompt setImage:[UIImage imageNamed:@"imdgdhh.png"]];
    imgPrompt.layer.borderWidth = 1.0;
    imgPrompt.layer.borderColor = [[UIColor clearColor]CGColor];
    imgPrompt.clipsToBounds = YES;
    imgPrompt.layer.cornerRadius = 20.0;
    [_promptView addSubview:imgPrompt];
    
    //提示文字
    UILabel *labPrompt = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, kScreenWidth, 30)];
    labPrompt.backgroundColor = [UIColor clearColor];
    labPrompt.textColor = [UIColor colorWithWhite:0.256 alpha:1.000];
    labPrompt.font = [UIFont boldSystemFontOfSize:17.0f];
    labPrompt.textAlignment = NSTextAlignmentCenter;
    labPrompt.text = @"抱歉,没有找到相关视频";
    [_promptView addSubview:labPrompt];
    
}


//历史搜索和热门搜索
-(void)addHotView
{
    UIView *viewA = [[UIView alloc]init];
    [self.view addSubview:viewA];
    
    _tableHot = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+55, kScreenWidth, kScreenHeight-64-55-48) style:UITableViewStyleGrouped];
    _tableHot.showsVerticalScrollIndicator = NO;//隐藏纵向滚动条
    _tableHot.delegate = self;
    _tableHot.dataSource = self;
    _tableHot.bounces = NO;
    [_tableHot setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableHot setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
    [self.view addSubview:_tableHot];
}

-(void)limitLength:(UITextField *)sender{
    if (_isChinese == YES && _flag == YES) {
        UITextRange *range = _txtSearch.selectedTextRange;
        int pos = [_txtSearch offsetFromPosition:_txtSearch.endOfDocument toPosition:range.end];
        NSString *strSearch = [_txtSearch.text substringFromIndex:pos];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
            //从网络接口查询词条信息
            _arrSearch = [NetWorkingHelper getSearchWithWords:strSearch];
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程更新UI
                [_tableSearch reloadData];
                [UIView animateWithDuration:0.2f animations:^{
                    _searchBgView.layer.borderColor = [[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.000]CGColor];
                    _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64-48);
                    _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, kScreenHeight-64-48-55);
                }];
            });
        });
    }
}

//搜索按钮的方法
-(void)clickSearch
{
    if (_flag == NO && _txtSearch.text.length != 0)
    {
        _flag = YES;
        [_btnSearch setImage:nil forState:UIControlStateNormal];
        [_btnSearch setTitle:MyLocalizedString(@"cancel") forState:UIControlStateNormal];
    }
    else
    {
        _flag = NO;
        [_txtSearch resignFirstResponder];
        _txtSearch.placeholder = MyLocalizedString(@"input2");
        [_btnSearch setTitle:@"" forState:UIControlStateNormal];
        [_btnSearch setImage:[UIImage imageNamed:@"Search.png"]forState:UIControlStateNormal];
        _searchBgView.layer.borderColor = [[UIColor clearColor]CGColor];
        _txtSearch.text = @"";
    }
    
    
    //从数据库查询历史记录信息
    _arrHistory  = [DBDaoHelper selectSearchHistory];
    _arrHHH = [[NSMutableArray alloc]init];
    for (int i = _arrHistory.count-1; i >= 0; i--) {
        [_arrHHH addObject:[_arrHistory objectAtIndex:i]];
    }
    
    [UIView animateWithDuration:0.2f animations:^{
        _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, 0);
        _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
        _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, 55);
        [_arrSearch removeAllObjects];//移除元素
        [_tableSearch reloadData];
        [_tableHot reloadData];
    }];

}

-(void)textFieldDidBeginAction
{
    _flag = YES;
    [_btnSearch setImage:nil forState:UIControlStateNormal];
    [_btnSearch setTitle:MyLocalizedString(@"cancel") forState:UIControlStateNormal];
    _txtSearch.placeholder = @"";
    _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
}

//开始输入
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    _flag = YES;
    [_btnSearch setImage:nil forState:UIControlStateNormal];
    [_btnSearch setTitle:MyLocalizedString(@"cancel") forState:UIControlStateNormal];
    _txtSearch.placeholder = @"";
    _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
}

//正在输入
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_flag == YES && _isChinese == NO) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //执行耗时操作
            //从网络接口查询词条信息
            if (range.length == 0 && range.location == 0) {
                _arrSearch = [NetWorkingHelper getSearchWithWords:string];
            }
            else{
                _arrSearch = [NetWorkingHelper getSearchWithWords:_txtSearch.text];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //主线程更新UI
                [_tableSearch reloadData];
                [UIView animateWithDuration:0.2f animations:^{
                    _searchBgView.layer.borderColor = [[UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.000]CGColor];
                    _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64-48);
                    _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, kScreenHeight-64-48-55);
                }];
            });
        });
    }
    return YES;
}

//结束编辑
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_flag == NO) {
        [UIView animateWithDuration:0.2f animations:^{
            _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
            _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, 0);
            _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, 55);
            [_arrSearch removeAllObjects];//移除元素
            [_tableSearch reloadData];
        }];
    }
    else if (_flag == YES) {
        [UIView animateWithDuration:0.2f animations:^{
            _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64-48);
            _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, kScreenHeight-64-48-55);
            
            if (_arrSearch.count == 0) {
                [UIView animateWithDuration:0.2f animations:^{
                    _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 100);
                }];
            }
        }];
    }
}

-(void)textFieldDidEndAction
{
    if (_flag == NO) {
        [UIView animateWithDuration:0.2f animations:^{
            _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
            _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, 0);
            _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, 55);
            [_arrSearch removeAllObjects];//移除元素
            [_tableSearch reloadData];
        }];
    }
    else if (_flag == YES) {
        [UIView animateWithDuration:0.2f animations:^{
            _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64-48);
            _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, kScreenHeight-64-48-55);
            
            if (_arrSearch.count == 0) {
                [UIView animateWithDuration:0.2f animations:^{
                    _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 100);
                }];
            }
        }];
    }
}

//清除
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    _txtSearch.text = @"";
    [UIView animateWithDuration:0.2f animations:^{
        _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 0);
        _tableSearch.frame = CGRectMake(0, 55, kScreenWidth, 0);
        _searchBgView.frame = CGRectMake(0, 64, kScreenWidth, 55);
        [_arrSearch removeAllObjects];//移除元素
        [_tableSearch reloadData];
    }];
    return YES;
}


//分组自定义
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableSearch)
    {
        return nil;
    }
    else
    {
        if (section == 0) {
            //历史搜素lab
            UILabel *labName = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
            labName.backgroundColor = [UIColor clearColor];
            [labName setUserInteractionEnabled:YES];
            labName.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.000];
            labName.font = [UIFont systemFontOfSize:17.0f];
            labName.text = MyLocalizedString(@"historicalsearch");
            
            //清除按钮
            UIButton *btnClean = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btnClean.frame = CGRectMake(kScreenWidth-5-40, 0, 40, 40);
            btnClean.tintColor = [UIColor colorWithWhite:0.472 alpha:1.000];
            [btnClean setImage:[UIImage imageNamed:@"clean.png"] forState:UIControlStateNormal];
            btnClean.backgroundColor = [UIColor clearColor];
            [btnClean addTarget:self action:@selector(clickClean) forControlEvents:UIControlEventTouchUpInside];
            [labName addSubview:btnClean];
            return labName;
        }
        else{
            UILabel *labHot = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
            labHot.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
            labHot.font = [UIFont systemFontOfSize:17.0f];
            labHot.textColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.000];
            labHot.text = MyLocalizedString(@"highlightedsearch");
            return labHot;
        }
    }
}


//列表每行显示的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //row 代表列表的那一行
    int section = (int)[indexPath section];
    int row = (int)[indexPath row];
    
    if (tableView ==_tableSearch)
    {
        UIView *viewLine = [[UIView alloc]init];
        viewLine.frame = CGRectMake(15 , 0, kScreenWidth-15, 0.5);
        viewLine.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:1.000];
        [tableView addSubview:viewLine];
        
        Search *searchInfo = [_arrSearch objectAtIndex:row];
        if (searchInfo.flag == 88) {
            NSString *identifierSearch = @"searchTable";
            //获取cell row ＝ 0 获取不到 进入创建cell
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierSearch];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifierSearch];
                [cell setBackgroundColor:[UIColor colorWithWhite:0.974 alpha:1.000]];
                cell.selectionStyle = UITableViewCellSelectionStyleGray;
            }
            
            //搜索词变色
            NSRange rangeStr = [searchInfo.strTitle rangeOfString:_txtSearch.text];
            NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:searchInfo.strTitle];
            [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.200 green:0.447 blue:1.000 alpha:1.000] range:rangeStr];
            cell.textLabel.attributedText = AttributedStr;
            return cell;
        }
        else{
            NSString *identifierSearch = @"searchTableCELL";
            //获取cell row ＝ 0 获取不到 进入创建cell
            SearchTableViewCell *seaCell = [tableView dequeueReusableCellWithIdentifier:identifierSearch];
            if (seaCell == nil)
            {
                seaCell = [[SearchTableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifierSearch];
                [seaCell setBackgroundColor:[UIColor colorWithWhite:0.974 alpha:1.000]];
                seaCell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            if (![searchInfo.strThumbnail isKindOfClass:[NSNull class]] && searchInfo.strThumbnail.length > 0)
            {//不是空字符串的
                [seaCell.imageVoide setImageWithURL:[NSURL URLWithString:searchInfo.strThumbnail] placeholderImage:[UIImage imageNamed:@"poster_default.png"]];
            }
            else{//空串
                [seaCell.imageVoide setImage:[UIImage imageNamed:@"poster_default.png"]];
            }
            seaCell.labTitle.text = searchInfo.strTitle;
            seaCell.labClass.text = searchInfo.strCategoryName;
            
            //过滤html标签
            searchInfo.strDescription = [self flattenHTML:searchInfo.strDescription];
            if (searchInfo.strDescription.length == 0) {
                seaCell.labDescription.text = MyLocalizedString(@"desc0");
                seaCell.labDescription.numberOfLines = 1;
                seaCell.labDescription.frame = CGRectMake(145, 58, kScreenWidth-145-15, 20);
            }
            else{
                seaCell.labDescription.numberOfLines = 3;
                seaCell.labDescription.frame = CGRectMake(145, 55, kScreenWidth-145-15, 60);
                seaCell.labDescription.text = searchInfo.strDescription;
            }
            return seaCell;
        }
    }
    else
    {
        if (section == 0)
        {
            NSString *identifierHistory = @"historyTable";
            //获取cell row ＝ 0 获取不到 进入创建cell
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifierHistory];
            [cell setBackgroundColor:[UIColor clearColor]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            //历史记录
            for (int i = 1; i < _arrHistory.count+1; i++)
            {
                UIButton *btnHistory = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                if (i % 2 != 0){
                    btnHistory.frame = CGRectMake(15, 5+40*((i-1)/2), (kScreenWidth-15*2-10)/2, 30);
                }
                else{
                    btnHistory.frame = CGRectMake(15+(kScreenWidth-15*2-10)/2+10, 5+40*((i-1)/2), (kScreenWidth-15*2-10)/2, 30);
                }
                [btnHistory setUserInteractionEnabled:YES];
                btnHistory.backgroundColor = [UIColor clearColor];
                btnHistory.layer.cornerRadius = 5.0;
                btnHistory.layer.borderWidth = 1.0;
                btnHistory.layer.borderColor = [[UIColor colorWithWhite:0.662 alpha:1.000]CGColor];
                btnHistory.clipsToBounds = YES;
                btnHistory.tag = 101 + i;
                [btnHistory addTarget:self action:@selector(clickHistory:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnHistory];
                
                UILabel *labHistory = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, (kScreenWidth-15*2-10)/2, 30)];
                labHistory.backgroundColor = [UIColor clearColor];
                labHistory.font = [UIFont systemFontOfSize:16.0f];
                Search *se = [_arrHistory objectAtIndex:_arrHistory.count-i];
                labHistory.text = se.strTitle;
                labHistory.textColor = [UIColor blackColor];
                labHistory.textAlignment = NSTextAlignmentCenter;
                [btnHistory addSubview:labHistory];
            }
            return cell;
        }
        else{
            NSString *identifierHot = @"hotTable";
            //获取cell row ＝ 0 获取不到 进入创建cell
            ClassTableViewCell *cell = [[ClassTableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifierHot];
            [cell setBackgroundColor:[UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UILabel *labCircle = [[UILabel alloc]init];
            labCircle.text = [NSString stringWithFormat:@"%d",row+1];
            if (row == 0)
            {
                labCircle.backgroundColor = [UIColor redColor];
            }
            else if (row == 1)
            {
                labCircle.backgroundColor = [UIColor orangeColor];
            }
            else if (row == 2)
            {
                labCircle.backgroundColor = [UIColor colorWithRed:0.897 green:0.896 blue:0.002 alpha:1.000];
            }
            else
            {
                labCircle.backgroundColor = [UIColor lightGrayColor];
            }
            labCircle.textAlignment = NSTextAlignmentCenter;
            labCircle.frame = CGRectMake(20 , 10, 25, 25);
            labCircle.layer.borderColor = [[UIColor clearColor]CGColor];
            labCircle.layer.cornerRadius = 5.0;
            labCircle.layer.borderWidth = 1.5;
            labCircle.textColor = [UIColor whiteColor];
            labCircle.clipsToBounds = YES;//内容不超出边框
            [cell addSubview:labCircle];
            
            
            cell.labClassName.frame = CGRectMake(55, 0, kScreenWidth-55, 45);
            cell.labClassName.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.000];
            HotWords *hot = [_arrHot objectAtIndex:row];
            cell.labClassName.text = hot.strHotWordsName;
            return cell;
        }
    }
}

//过滤html标签
- (NSString *)flattenHTML:(NSString *)strhtml
{
    NSString *text = nil;
    NSScanner *theScanner = [NSScanner scannerWithString:strhtml];
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        strhtml = [strhtml stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    } // while //
    return strhtml;
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableSearch)
    {
        //点击联想列表搜索词条
        Search *searchInfo = [_arrSearch objectAtIndex:indexPath.row];
        if ([searchInfo.strId intValue] == 0) {
            _txtSearch.text = searchInfo.strTitle;
//            [_txtSearch becomeFirstResponder];
            [self textFieldDidBeginAction];
        }
        else if (searchInfo.flag == 88) {
            _txtSearch.text = searchInfo.strTitle;
//            [_txtSearch becomeFirstResponder];
            [self textFieldDidBeginAction];
        }
        
        RequestParameter *rep = [[RequestParameter alloc]init];
        rep.portID = 5;
        rep.strCategoryID = @"";
        rep.strPageNo = @"1";
        rep.strPageSize = @"30";
        rep.strSearchWords = _txtSearch.text;
        
        [Loading showLoadingWithView:self.view];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
            //从网络接口查询词条信息
            _arrSearch = [NetWorkingHelper getSearchBtnWithRep:rep];
            dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
                [Loading hiddonLoadingWithView:self.view];
                [_tableSearch reloadData];
                [_txtSearch resignFirstResponder];
//                [self textFieldDidEndAction];
            });
        });
        
        if ([searchInfo.strId intValue] != 0) {
            DetailViewController *detail = [[DetailViewController alloc]initWithResId:searchInfo.strId];
            detail.strTitle = searchInfo.strTitle;
            detail.strIndex = @"1";
            detail.strSource = @"";
            [self.navigationController pushViewController:detail animated:YES];
        }
        else {
            //从数据库查询历史记录信息
            NSMutableArray *arrHist = [DBDaoHelper selectSearchHistory];
            if (arrHist.count == 5)
            {
                //删除数据库中的第一条数据
                [DBDaoHelper deleteSearchHistoryMin];
            }
            
            //历史记录添加到数据库
            [DBDaoHelper insertSearchHistory:searchInfo];
        }
    }
    else
    {
        if (indexPath.section == 0) {
        }
        else{
            //点击热词列表进入详情页
            HotWords *hot = [_arrHot objectAtIndex:indexPath.row];
            _txtSearch.text = hot.strHotWordsName;
//            [_txtSearch becomeFirstResponder];
            [self textFieldDidBeginAction];
            
            RequestParameter *rep = [[RequestParameter alloc]init];
            rep.portID = 5;
            rep.strCategoryID = @"";
            rep.strPageNo = @"1";
            rep.strPageSize = @"30";
            
            rep.strSearchWords = _txtSearch.text;
            [Loading showLoadingWithView:self.view];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
                //从网络接口查询词条信息
                _arrSearch = [NetWorkingHelper getSearchBtnWithRep:rep];
                dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
                    [Loading hiddonLoadingWithView:self.view];
                    [_tableSearch reloadData];
                    [_txtSearch resignFirstResponder];
                    [self textFieldDidEndAction];
                    
                    if (_arrSearch.count == 0) {
                        [UIView animateWithDuration:0.2f animations:^{
                            _promptView.frame = CGRectMake(0, 64+55, kScreenWidth, 100);
                        }];
                    }
                });
            });
            Search *searchInfo = [[Search alloc] init];
            searchInfo.strTitle = [rep strSearchWords];
            //从数据库查询历史记录信息
            NSMutableArray *arrHist = [DBDaoHelper selectSearchHistory];
            if (arrHist.count == 5)
            {
                //删除数据库中的第一条数据
                [DBDaoHelper deleteSearchHistoryMin];
            }
            
            //历史记录添加到数据库
            [DBDaoHelper insertSearchHistory:searchInfo];
        }
    }
}

//当滑动table时
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _tableSearch){
        [_txtSearch resignFirstResponder];
    }
}

//返回分组的个数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _tableSearch)
    {
        return 1;
    }
    else
    {
        return 2;
    }
}

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableSearch)
    {
        return _arrSearch.count;
    }
    else
    {
        if (section == 0) {
            if (_arrHistory.count == 0) {
                return 0;
            }
            else{
                return 1;
            }
        }
        else{
            return _arrHot.count;
        }
    }
}

//列表每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableHot)
    {
        if (indexPath.section == 0) {
            if (_arrHistory.count%2 > 0) {
                return 40*(_arrHistory.count/2+1);
            }
            {
                return 40*_arrHistory.count/2;
            }
        }
    }
    else if (tableView == _tableSearch){
        Search *searchInfo = [_arrSearch objectAtIndex:indexPath.row];
        if (searchInfo.flag == 111) {
            return 120;
        }
        else{
            return 45;
        }
    }
    return 45;
}

//设置标题高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableSearch)
    {
        return 0;
    }
    else
    {
        return 40;
    }
}

//尾部标题的高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

//清除按钮的方法
-(void)clickClean
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfoe") delegate:self cancelButtonTitle:MyLocalizedString(@"cancel") otherButtonTitles:MyLocalizedString(@"sure"), nil];
    [alert show];
}

//清空历史记录
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1){
        //删除数据库中的所有数据
        [DBDaoHelper deleteSearchHistoryAll];
        //从数据库查询历史记录信息
        _arrHistory = [DBDaoHelper selectSearchHistory];
        [_tableHot reloadData];
    }
}

//历史记录按钮方法
-(void)clickHistory:(UIButton *)sender
{
    Search *searchInfo = [_arrHHH objectAtIndex:sender.tag-102];
    
    _txtSearch.text = searchInfo.strTitle;
//    [_txtSearch becomeFirstResponder];
    [self textFieldDidBeginAction];
    
    RequestParameter *rep = [[RequestParameter alloc]init];
    rep.portID = 5;
    rep.strCategoryID = @"";
    rep.strPageNo = @"1";
    rep.strPageSize = @"30";
    rep.strSearchWords = _txtSearch.text;
    
    [Loading showLoadingWithView:self.view];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
        //从网络接口查询词条信息
        _arrSearch = [NetWorkingHelper getSearchBtnWithRep:rep];
        dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
            [Loading hiddonLoadingWithView:self.view];
            [_tableSearch reloadData];
            [_txtSearch resignFirstResponder];
            [self textFieldDidEndAction];
        });
    });
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField//搜索按钮的事件
{
    if (_flag == YES && _txtSearch.text.length != 0) {
        RequestParameter *rep = [[RequestParameter alloc]init];
        rep.portID = 5;
        rep.strCategoryID = @"";
        rep.strPageNo = @"1";
        rep.strPageSize = @"30";
        rep.strSearchWords = _txtSearch.text;
        [Loading showLoadingWithView:self.view];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//执行耗时操作
            //从网络接口查询词条信息
            _arrSearch = [NetWorkingHelper getSearchBtnWithRep:rep];
            dispatch_async(dispatch_get_main_queue(), ^{//主线程更新UI
                [Loading hiddonLoadingWithView:self.view];
                [_tableSearch reloadData];
                [_txtSearch resignFirstResponder];
            });
        });
        Search *searchInfo = [[Search alloc] init];
        searchInfo.strTitle = [rep strSearchWords];
        //从数据库查询历史记录信息
        NSMutableArray *arrHist = [DBDaoHelper selectSearchHistory];
        if (arrHist.count == 5)
        {
            //删除数据库中的第一条数据
            [DBDaoHelper deleteSearchHistoryMin];
        }
        
        //历史记录添加到数据库
        [DBDaoHelper insertSearchHistory:searchInfo];
        
    }
    return YES;
}

//输入法发生切换
-(void)changeInputMode:(NSNotification *)notification{
    if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @"en-US"]) {
        _isChinese = NO;
    }
    else
    {
        _isChinese = YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
